package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AuthticationFilter
 */
public class AuthticationFilter implements Filter {
	public static final String SESS_USER = "loginUser";

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		String curentURI = httpRequest.getRequestURI();
		String targetURL = curentURI.substring(curentURI.indexOf("/", 1), curentURI.length());
		
		if (!"/".equals(targetURL) && !"/index.html".equals(targetURL)) {
			HttpSession session = httpRequest.getSession();
			if (session != null) {
				Object o = session.getAttribute(SESS_USER);
				if (o == null) {
					HttpServletResponse httpResponse = (HttpServletResponse) response;
					httpResponse.sendRedirect(httpRequest.getContextPath());
					return;
				}
			}
		}

		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	//@Override
	public void destroy() {
	}

	//@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
